package com.adnaan.backend.service.impl;

import com.adnaan.backend.common.exception.ServicesException;
import com.adnaan.backend.entity.Goods;
import com.adnaan.backend.mapper.GoodsMapper;
import com.adnaan.backend.service.GoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(Long id, Integer status) {
        Goods goods = getById(id);
        if (goods == null) {
            throw new ServicesException("商品不存在");
        }
        goods.setStatus(status);
        return updateById(goods);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStock(Long id, Integer stock) {
        Goods goods = getById(id);
        if (goods == null) {
            throw new ServicesException("商品不存在");
        }

        int newStock = goods.getStock() + stock;
        if (newStock < 0) {
            throw new ServicesException("库存不足");
        }

        goods.setStock(newStock);
        return updateById(goods);
    }

    @Override
    public boolean checkStock(Long id, Integer quantity) {
        Goods goods = getById(id);
        if (goods == null) {
            throw new ServicesException("商品不存在");
        }
        return goods.getStock() >= quantity;
    }

    @Override
    public List<Goods> getHotGoods() {
        // 获取订单下单量前5的商品id
        List<Long> goodsIds = baseMapper.getHotGoodsIds();
        if (goodsIds.isEmpty()) {
            return null;
        }
        return listByIds(goodsIds);
    }
} 